package fr.Orm.pierop.com;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import fr.dbManager.pierop.com.DBManager;
import fr.myExceptions.pierop.com.DBManagerSingletonException;
import fr.myExceptions.pierop.com.beanTypeException;
import fr.myExceptions.pierop.com.idTypeBeanException;

public class createByType implements IcreateByType {

	private DBManager	db;
	private Map<String, String>	typeToText;
	
	private static 	createByType singletonObject = null;
	
	private createByType() throws NoSuchMethodException, SecurityException, DBManagerSingletonException {
		this.db = DBManager.getInstance();
		this.typeToText = new HashMap<String, String>();
		this.typeToText.put(IcreateByType.typeInteger, IcreateByType.textInteger);
		this.typeToText.put(IcreateByType.typeString, IcreateByType.textString);
		this.typeToText.put(IcreateByType.typeDouble, IcreateByType.textDouble);
		this.typeToText.put(IcreateByType.typeFloat, IcreateByType.textFloat);
		}
	
	public static createByType	getInstance() throws NoSuchMethodException, SecurityException, DBManagerSingletonException {
		if (singletonObject == null) { singletonObject = new createByType(); }
		return singletonObject;
	}
	
	private boolean	ifColumnExists(String table, String col) throws SQLException
	{
		ResultSet r = this.db.execute("SHOW COLUMNS FROM " + table);
		while (r.next())
			if (r.getString("Field").equals(col)) return true;
		return false;
	}
	
	public	void createDB(String name, boolean verbose) throws SQLException
	{
		String query = "CREATE TABLE IF NOT EXISTS " + name + "( ID INT NOT NULL PRIMARY KEY )";
		this.db.update(query);
		if (verbose) { System.out.println("	[sql] " + query); }
	}
	
	public void createId(String name, String type, String table, boolean verbose) throws Exception
	{
		if (!type.equals(IcreateByType.typeInteger))
			throw new idTypeBeanException();
	}
	
	public	void createType(String name, String type, String table, boolean isId, boolean verbose) throws SQLException, beanTypeException {
		String query = "ALTER TABLE " + table;
		if (!this.ifColumnExists(table, name))
			query += " ADD COLUMN " + name + " ";
		else
			query += " MODIFY COLUMN " + name + " ";
		if (this.typeToText.get(type) == null) { throw new beanTypeException("Le Type " + type + " n'est pas gere dans les classes persistante du j-csi."); }
		query += this.typeToText.get(type) + " NULL";
		this.db.update(query);
		if (verbose) { System.out.println("	[sql] " + query); }
	}
}
